package com.egao.common.core.web;

import com.egao.common.module.system.entity.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Controller基类
 * @author system
 */
public class BaseController {

    /**
     * 获取当前登录的user
     */
    public User getLoginUser() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null) {
                return null;
            }

            Object object = authentication.getPrincipal();
            if (object != null) {
                return (User) object;
            }
        } catch (Exception e) {
            System.out.println("getLoginUser：" + e.getMessage());
        }
        return null;
    }

    /**
     * 获取当前登录的userId
     */
    public Integer getLoginUserId() {
        User loginUser = getLoginUser();
        return loginUser == null ? null : loginUser.getUserId();
    }

    /**
     * 验证是否有权限
     * @param authority 权限标识
     * @return 有权限true
     */
    public boolean hasAuthority(String authority) {
        long count = getLoginUser().getAuthorities().stream().filter(d -> authority.equals(d.getAuthority())).count();
        return count > 0;
    }

}
